package com.wheel.autoconfigure.web.mvc.swagger;/*
 * <h3>Title:ai-chiefcomplaint系统</h3>
 * <p>Copyright (c) 2021, wnfbx. All rights reserved.</p>
 * @author wnfbx
 */

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * <dt>Description:SwaggerAutoConfiguration</dt>
 * <dd>swagger 自动配置</dd>
 *
 * @author wnfbx
 * @version 1.0 <i>2021/8/6 14:14</i>
 * @since jdk1.7+
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@EnableConfigurationProperties(SwaggerAutoConfigureProperties.class)
public class SwaggerAutoConfiguration {

    private final SwaggerAutoConfigureProperties properties;

    public SwaggerAutoConfiguration(SwaggerAutoConfigureProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnProperty(value = "s.swagger.enable")
    public Docket createRestApi() {
        List<SwaggerAutoConfigureProperties.HeaderProperties> headerProperties = properties.getHeaderProperties();
        //添加head参数start
        List<Parameter> pars = new ArrayList<>(headerProperties.size());
        for (SwaggerAutoConfigureProperties.HeaderProperties headerPropertie : headerProperties) {
            pars.add(new ParameterBuilder().name(headerPropertie.getName()).description(headerPropertie.getDescription()).modelRef(new ModelRef(headerPropertie.getModelRef())).parameterType("header").required(headerPropertie.isRequired()).build());
        }
        //添加head参数end
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars)
                .apiInfo(properties.getApiInfo());
    }
}
